<?php
/**
 * 仓库公共模型
 * @author shipanpan
 *
 */
class Application_Model_Warehouse extends Model_Base {
	/**
	 * 获取全部的仓库
	 * @param  array  $field [description]
	 * @return [type]        [description]
	 */
	public function getAll(array $field = ['*']) {
		$db = $this->db();
		$select = $db->select();
		$select->from("c_warehouse", $field);
		return $db->fetchAll($select);
	}

	/**
	 * 获取仓库代码名称
	 * @param  string $warehouseCode [description]
	 * @return [type]                [description]
	 */
	public function getName(string $warehouseCode) {
		$warehouseName = $this->getWarehouseByCode($warehouseCode, ['warehouse_name']);
		if (!$warehouseName) {
			return $this->_error("未找到仓库代码为:" . $warehouseCode . "的仓库！");
			return false;
		} else {
			return $warehouseName[0]['warehouse_name'];
		}
	}

	/**
	 * 根据仓库代码获取仓库详情(支持批量获取)
	 * @param  [type] $warehouseCode 仓库代码，批量获取时传数组
	 * @param  array $fields         返回的字段
	 * @return [type]                [description]
	 */
	public function getWarehouseByCode($warehouseCode, array $fields = ["*"]) {
		$warehouseCode = is_array($warehouseCode) ? $warehouseCode : [$warehouseCode];
		$db = $this->db();
		$select = $db->select();
		$select->from("c_warehouse", $fields)->where('warehouse_code in(?)', $warehouseCode);
		return $db->fetchAll($select);
	}

	/**
	 * 根据仓库id获取仓库详情(支持批量获取)
	 * @param  [type] $warehouseCode 仓库主键id，批量获取时传数组
	 * @param  array $fields         返回的字段
	 * @return [type]              [description]
	 */
	public function getWarehouseById($warehouseId, array $fields = ["*"]) {
		$warehouseId = is_array($warehouseId) ? $warehouseId : [$warehouseId];
		$db = $this->db();
		$select = $db->select();
		$select->from("c_warehouse", $fields)->where('id in(?)', $warehouseId);
		return $db->fetchAll($select);
	}

	/**
	 * 根据仓库id获取仓库详情(支持批量获取)   用于HTML
	 * @param 仓库ID
	 */
	public function getWarehouseByIds($did) {

		$where = $did != 0 ? 'WHERE dept_id = ' . $did : '';
		return $this->db()->fetchAll('SELECT id, warehouse_name, warehouse_code FROM c_warehouse ' . $where);
	}

	/**
	 * 根据仓库名称取其信息
	 */
	public function getWareHouseInfoByWName($wname = '', $fields = '*') {

		if (!empty($name)) {
			$where = ' WHERE warehouse_name "' . $name . '" ';
		} else {
			$where = '';
		}
		return $this->db()->fetchAssoc('SELECT ' . $fields . ' FROM c_warehouse' . $where);
	}
	/**
	 * 根据仓库编码获取仓库的库存信息
	 * @param unknown $warehouse_code
	 * @param string $field
	 */
	public function getWareHouseStock($warehouse_code, $goods_sn, $field = 'base_stock,stock_on_way') {
		$sql = "select ". $field ." from p_product_warehouse_stock where goods_sn=:sku and warehouse_code = :code";
		return $this->db()->fetchRow($sql, ['code'=>$warehouse_code,'sku'=>$goods_sn]);
	}
}